const express = require("express");
const app = express();
var http = require("http");
var Client = require("ssh2").Client;
var conn = new Client();
conn.connect({
  host: "47.103.36.143",
  port: 22,
  username: "root",
  password: "wmg123WMG"
});

var socketIo = require("socket.io"); //引入socket.io

app.use("/static", express.static("public"));

var server = http.createServer(app);
var io = new socketIo(server); //将socket.io注入express模块

app.get("/", (req, res) => res.send("Hello World!"));

app.get("/index", (req, res) => {
  res.sendFile(__dirname + "/views/index.html");
});
app.get("/01", (req, res) => {
  res.sendFile(__dirname + "/views/01.html");
});

server.listen(8888, () => console.log("Example app listening on port 8888!"));

//每个客户端socket连接时都会触发 connection 事件
io.on("connection", function(clientSocket) {
  doConn(clientSocket);
  // socket.io 使用 emit(eventname,data) 发送消息，使用on(eventname,callback)监听消息

  //监听客户端发送的 sendMsg 事件
  clientSocket.on("client_server_msg", function(data) {
    // data 为客户端发送的消息，可以是 字符串，json对象或buffer

    console.log(data.msg, "=======data.msg======");
    exec(data.msg,clientSocket);
  });
});

var abc;
function exec(execStr,clientSocket) {
  console.log("==============exec=============");

  var sensiveStr = ["rm", "vim"];
  var has = false;

  for (let i = 0; i < sensiveStr.length; i++) {
    if (execStr.indexOf(sensiveStr[i]) > -1) {
      has = true;
      break;
    }
  }
  if (has) {
    var result = {
      client: "王孟贵",
      msg: "senssive word in or no support now ! " + "\n"
    };
    clientSocket.emit("server_client_msg", result);
  } else {
    abc.write(execStr + "\n");
    return false;
  }
}

function doConn(clientSocket) {
  conn.shell(function(err, stream) {
    if (err) throw err;
    stream
      .on("close", function() {
        console.log("Stream :: close");
        // conn.end();
      })
      .on("data", function(data) {
        console.log(data.toString());

        var result = {
          client: "王孟贵",
          msg: data.toString()
        };

        // sockets.emit("server_client_msg", result);
        clientSocket.emit("server_client_msg", result);

        console.log("==============on.data=============");
      })
      .stderr.on("data", function(data) {
        // console.log("STDERR: " + data);
      });

    abc = stream;
    // stream.write(execStr + "\n ls -l\nexit\n");
  });
}
